import logging

from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer

logger = logging.getLogger()


class ServerMonitorWebsocket(JsonWebsocketConsumer):
    websocket_list = []

    def __init__(self, *args, **kwargs):
        self.group_name = 'server_monitor_group'
        super().__init__(*args, **kwargs)

    def connect(self):
        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.group_name,
            self.channel_name
        )
        self.accept()
        ServerMonitorWebsocket.websocket_list.append(self)
        logger.info('服务器：服务器监控Websocket已连接，现共有%d个客户端' % len(ServerMonitorWebsocket.websocket_list))

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.group_name,
            self.channel_name
        )
        ServerMonitorWebsocket.websocket_list.remove(self)
        logger.info('服务器：服务器监控Websocket断开连接，现共有%d个客户端' % len(ServerMonitorWebsocket.websocket_list))

    # Receive message from room group
    def server_monitor(self, event):
        data = event['data']
        # Send message to WebSocket
        self.send_json(data)
